package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"product2/model/mysql"
	"product2/model/redis"
	"product2/userrpc/internal/svc"
	"product2/userrpc/userrpc"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *userrpc.ListRequest) (*userrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var pro []mysql.Product

	get := redis.Client.Get("List")

	if get.Val() == "" {
		mysql.DB.Offset(int(offset)).Limit(int(pageSize)).Order("price desc").Order("created_at desc").Find(&pro)

		marshal, _ := json.Marshal(pro)

		redis.Client.Set("List", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &pro)
	}

	var product []*userrpc.List
	for _, i2 := range pro {
		list := userrpc.List{
			Id:      int64(i2.ID),
			Name:    i2.Name,
			Img:     i2.Img,
			Number:  i2.Number,
			Price:   i2.Price,
			UserId:  i2.UserId,
			Details: i2.Details,
			Title:   i2.Title,
			Text:    i2.Text,
		}
		product = append(product, &list)
	}
	return &userrpc.ListResponse{List: product}, nil
}
